package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"strconv"
)

type Object struct {
	Obj_id  string `json:"obj"`
	Content []byte `json:"content"`
}

func ReadFromOtherClusters(IP string, port int, obj string, offset int, length int) []byte {
	url := "http://" + IP + ":" + strconv.Itoa(port) + "/get?oid=" + obj + "&off=" + strconv.Itoa(offset) + "&len=" + strconv.Itoa(length)
	fmt.Println(url)
	resp, err := http.Get(url)
	if err != nil {
		return nil
	}
	defer resp.Body.Close()
	ret, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil
	}
	return ret
}

func WriteToOtherClusters(IP string, port int, obj_id string, content []byte) error {
	url := "http://" + IP + ":" + strconv.Itoa(port) + "/put"
	obj := Object{
		Obj_id:  obj_id,
		Content: content,
	}
	obj_json, err := json.Marshal(obj)
	if err != nil {
		return err
	}

	resp, err := http.Post(url, "application/json", bytes.NewBuffer(obj_json))
	if err != nil {
		return err
	}
	resp_body, _ := ioutil.ReadAll(resp.Body)
	fmt.Printf("write obj: %s to %s, length: %d, resp: %s\n", obj_id, url, len(obj.Content), string(resp_body))
	return nil
}

func main() {
	IP := "10.10.9.47"
	port := 8080
	obj := "1a1cbf29-00c1-449c-9935-8fd90291a9b2.4369.1__shadow_.TD8wUMuvME2CXpEfh32_kxSHaHSLbSf_3"
	offset := 0
	length := 4194304

	f, err := os.OpenFile(os.Getenv("HOME")+"/read_from_ceph", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0664)
	if err != nil {
		return
	}
	_, err = f.Write(ReadFromOtherClusters(IP, port, obj, offset, length))
	if err != nil {
		return
	}
	f.Close()

	f, err = os.OpenFile(os.Getenv("HOME")+"/read_from_ceph", os.O_RDONLY, 0664)
	if err != nil {
		return
	}
	defer f.Close()

	content, err := ioutil.ReadAll(f)
	if err != nil {
		return
	}
	if err = WriteToOtherClusters(IP, port, "test_object_0", content); err != nil {
		fmt.Println("Write to other cluster error" + err.Error())
		return
	}
}
